package com.csailing4cloud.csailing.common.feign.hystrix;

import com.csailing4cloud.csailing.common.core.constants.CommonConstants;
import com.csailing4cloud.csailing.common.core.util.CsResponse;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;
import org.springframework.lang.Nullable;

import java.lang.reflect.Method;

/**
 * @author
 */
@Slf4j
@AllArgsConstructor
public class CsailingFeignFallbackMethod implements MethodInterceptor {

	private Class<?> type;
	private Throwable cause;

	@Nullable
	@Override
	public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) {
		log.error("Fallback class:[{}] method:[{}] message:[{}]",
				type.getName(), method.getName(), cause.getMessage());

		if (CsResponse.class == method.getReturnType()) {
			final CsResponse result = cause instanceof CsailingFeignException ?
					((CsailingFeignException) cause).getResult() : CsResponse.builder()
					.code(CommonConstants.FAIL)
					.message(cause.getMessage()).build();
			return result;
		}
		return null;
	}
}
